﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using WxTenpay.Common;
using WxTenpay.Service;
using WXApi.Model;
using Microsoft.AspNetCore.Cors;
using WxTenpay.Service.Model;
using System.Transactions;

namespace WXApi.Controllers
{
    /// <summary>
    /// 获取用户数据
    /// </summary>
    /// 
    [Route("[controller]/[action]")]
    [ApiController]
    [Action]
    public class SysUserApiController : ReqDataControllerBase
    {
        private readonly ISysMenu sysmenu;
        private readonly ISysMenuButton sysmenubutton;
        private readonly ISysUser sys_user;
        private readonly ISysRole _isysrole;
        private readonly ISysRoleAuthorization isysroleauthorization;
        private readonly ISysLog syslog;
        private readonly ISysLoginLog sysloginlog;
        public SysUserApiController(ISysLog _syslog, ISysLoginLog _sysloginlog, ISysMenu _sysmenu, ISysMenuButton _sysmenubutton, ISysUser _sysuser, ISysRoleAuthorization _isysroleauthorization, ISysRole isysrole)
        {
            sys_user = _sysuser;
            sysmenu = _sysmenu;
            sysmenubutton = _sysmenubutton;
            isysroleauthorization = _isysroleauthorization;
            _isysrole = isysrole;
            syslog = _syslog;
            sysloginlog = _sysloginlog;
        }


        /// <summary>
        /// 获取基本信息 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult GetUsermodel()
        {
            try
            {

                var token = HttpContext.Items["token"].ToString();
                if (string.IsNullOrWhiteSpace(token))
                    return Error("参数错误！");


                var _token = GetUser(token);//获取用户信息

                var data = new
                {
                    name = "测试",
                    idnumber = "123213",

                };


                return Success(data);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/GetUsermodel", Content = ex.ToString(), Name = "获取基本信息" };
                return ErrorLog(model);

            }
        }

        #region 权限管理
        /// <summary>
        /// 获取用户菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetUserMenu(string gid)
        {
            try
            {
                var token = HttpContext.Items["token"].ToString();
                //登入账号信息
                var userguid = GetUser(token);
                var btnlis = sysmenubutton.GetList();
                var list = sysmenu.GetList().Select(x =>
                {
                    x.buttons = btnlis.Where(p => p.MenuGuId == x.GuId).ToList();
                    return x;
                }).ToList();


                //获取当前用户的信息
                var usermodel = sys_user.GetModel(x => x.GuId == gid);
                if (usermodel == null)
                    return Error("参数异常！");

                List<SysRoleAuthorizationEntity> userRoleAuthorization = new List<SysRoleAuthorizationEntity>();
                if (usermodel.UserName == "admin") //超级管理员
                {
                    list.ForEach(x =>
                    {
                        var ButtonLis = "";

                        if (x.buttons != null)
                            ButtonLis = string.Join(',', x.buttons.Select(p => { return p.GuId; }));
                        userRoleAuthorization.Add(new SysRoleAuthorizationEntity { MenuGid = x.GuId, ButtonLis = ButtonLis, UserGid = usermodel.GuId });

                    });
                }
                else
                {     //获取用户权限
                    userRoleAuthorization = isysroleauthorization.GetList(x => x.UserGid == gid);
                }

                var rdata = new
                {
                    list,
                    userRoleAuthorization = userRoleAuthorization.Select(x =>
                    {
                        return new
                        {
                            x.MenuGid,
                            x.ButtonLis,
                            x.UserGid
                        };
                    })
                };

                return Success(rdata);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/GetUserMenu", Content = ex.ToString(), Name = "获取用户菜单数据" };
                return ErrorLog(model);

            }
        }
        #endregion




        /// <summary>
        /// 获取用户列表信息 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult GetUserList([FromBody] PageModel.PageParm parm)
        {
            try
            {
                var data = sys_user.GetRolePages(parm);
                return Success(data);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/GetUserList", Content = ex.ToString(), Name = "获取用户列表信息" };
                return ErrorLog(model);
            }
        }


        /// <summary>
        /// 获取用户列表信息 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult AddUser([FromBody] SysUserEntity entity)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(entity.GuId))
                {     //新增

                    if (sys_user.GetModel(x => x.UserName == entity.UserName) != null)
                    {
                        entity.Create();
                        entity.Password = DESEncrypt.MD5Encrypt(entity.Password);
                        sys_user.Add(entity);
                    }
                    else
                        return Error("对不起您的登入账号已存在！");

                }
                else
                {   //修改信息
                    var model = sys_user.GetModel(x => x.GuId == entity.GuId);
                    if (model != null)
                    {
                        model.IsDel = entity.IsDel;
                        model.Name = entity.Name;
                        model.RoleGuId = entity.RoleGuId;
                        model.NickName = entity.NickName;
                        model.DepartmentGuId = entity.DepartmentGuId;
                        model.CompanyGuId = entity.CompanyGuId;
                        sys_user.Update(model);
                    }
                }

                return Success("操作成功！");
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/AddUser", Content = ex.ToString(), Name = "新增用户信息" };
                return ErrorLog(model);
            }
        }


        /// <summary>
        /// 重置密码 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult ResetPwd(string gid)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(gid))
                {     //新增

                    var model = sys_user.GetModel(x => x.GuId == gid);
                    model.Password = DESEncrypt.MD5Encrypt("sys@123456");//默认密码
                    sys_user.Update(model);

                    SuccessLogDto loginmodel = new SuccessLogDto();
                    loginmodel.data = "操作成功";
                    loginmodel._sysloginlog = sysloginlog;
                    loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 2, Content = $"{model.Name}=》重置密码" };
                    return SuccessLog(loginmodel);
                }
                else return Error("参数异常！");

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/ResetPwd", Content = ex.ToString(), Name = "重置密码" };
                return ErrorLog(model);
            }
        }




        /// <summary>
        /// 修改状态 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult ModifyState(string gid)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(gid))
                {     //编辑

                    var model = sys_user.GetModel(x => x.GuId == gid);
                    if (model == null)
                        return Error("参数异常！");

                    if (model.UserName == "admin")
                        return Error("超级管理员不能禁用！");

                    model.IsDel = model.IsDel == 0 ? 1 : 0;
                    sys_user.Update(model);


                    string status = model.IsDel == 0 ? "正常" : "禁用";
                    SuccessLogDto loginmodel = new SuccessLogDto();
                    loginmodel.data = "操作成功";
                    loginmodel._sysloginlog = sysloginlog;
                    loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 2, Content = $"{model.Name}=》修改状态（{status}）" };
                    return SuccessLog(loginmodel);
                }
                else return Error("参数异常！");

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/ModifyState", Content = ex.ToString(), Name = "修改状态" };
                return ErrorLog(model);

            }
        }


        /// <summary>
        /// 获取角色列表 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult GetRoles()
        {
            try
            {
                var lis = _isysrole.GetList().Select(x => { return new { x.GuId, x.Name, x.Number }; });
                return Success(lis);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/GetRoles", Content = ex.ToString(), Name = "获取角色列表" };
                return ErrorLog(model);
            }
        }



        /// <summary>
        /// 修改用户权限 
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult ModifyPermissions([FromBody] List<SysRoleAuthorizationEntity> lis, [FromQuery] string gid)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(gid)) return Error("参数异常！");




                var model = sys_user.GetModel(x => x.GuId == gid);
                if (model.UserName == "admin") {
                    return Error("超级管理员无法操作！");
                }



                using (TransactionScope tran = new TransactionScope())
                {
                    int count = isysroleauthorization.Delete(x => x.UserGid == gid);

                    lis.ForEach(x =>
                    {
                        x.Create();
                        x.UserGid = gid;
                        x.Type = 0;
                        isysroleauthorization.Add(x);
                    });
                    tran.Complete();
                }

                SuccessLogDto loginmodel = new SuccessLogDto();
                loginmodel.data = "操作成功";
                loginmodel._sysloginlog = sysloginlog;
                loginmodel.loginlogmodel = new SysLoginLogEntity { Type = 2, Content = $"{gid}=》修改用户权限" };
                return SuccessLog(loginmodel);

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = syslog;
                model.logmodel = new SysLogEntity { Action = "SysUserApi/ModifyPermissions", Content = ex.ToString(), Name = "修改用户权限" };
                return ErrorLog(model);
            }
        }






        /// <summary>
        /// 获取菜单列表数据
        /// </summary>
        /// <param name="lis"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        private object getmenu(List<SysMenuEntity> lis, List<SysMenuButtonEntity> btnlis, string ParentId = "0")
        {
            try
            {
                var list = lis.Where(x => x.ParentId == ParentId).Select(x =>
                {
                    return new
                    {
                        Id = x.Id,
                        GuId = x.GuId,
                        Icon = x.Icon,
                        Name = x.Name,
                        Type = x.Type,
                        Address = x.Address,
                        Sort = x.Sort,
                        ParentId = x.ParentId,
                        Btnlis = btnlis.Where(p => p.MenuGuId == x.GuId),
                        children = getmenu(lis, btnlis, x.Id.ToString())
                    };


                });

                return list;

            }
            catch (Exception)
            {

                throw;
            }

        }

    }



}